package com.gimi.cloud.jimi.manage.service.app.impl;

import com.gimi.cloud.jimi.common.enums.CommonEnume;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.Page;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.commonService.common.JmOperationLogService;
import com.gimi.cloud.jimi.dao.dao.homePage.AdDao;
import com.gimi.cloud.jimi.dao.dao.homePage.ColumnDao;
import com.gimi.cloud.jimi.dao.dao.homePage.ColumnProdDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductStatusDao;
import com.gimi.cloud.jimi.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.jimi.dto.app.AdDTO;
import com.gimi.cloud.jimi.dto.app.ColumnProdDTO;
import com.gimi.cloud.jimi.dto.base.BaseDTO;
import com.gimi.cloud.jimi.dto.product.ProductDto;
import com.gimi.cloud.jimi.dto.product.ProductStatusDTO;
import com.gimi.cloud.jimi.entity.app.AdEntity;
import com.gimi.cloud.jimi.entity.app.ColumnEntity;
import com.gimi.cloud.jimi.manage.service.app.AdService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @auther loongs
 * @date 2017/12/27  15:43
 */
@Service
public class AdServiceImpl implements AdService {
    private AdDao adDao;
    private ColumnDao columnDao;
    private ColumnProdDao columnProdDao;
    private ProductDao productDao;
    private ProductStatusDao productStatusDao;
    private JmOperationLogService jmOperationLogService;
    private static Logger logger = LoggerFactory.getLogger(AdServiceImpl.class);

    @Autowired
    public AdServiceImpl(AdDao adDao, ColumnDao columnDao, JmOperationLogService jmOperationLogService,
                         ProductStatusDao productStatusDao, ColumnProdDao columnProdDao, ProductDao productDao) {
        this.adDao = adDao;
        this.columnDao = columnDao;
        this.jmOperationLogService = jmOperationLogService;
        this.columnProdDao = columnProdDao;
        this.productDao = productDao;
        this.productStatusDao = productStatusDao;
    }

    @Override
    public Page<AdDTO> getAdList(AdDTO adDTO) {
        PageHelper.startPage(adDTO.getCurrentPage(), adDTO.getPageSize());
        long startTime = System.currentTimeMillis();
        List<AdDTO> result = adDao.queryPageList(adDTO);
        long endTime = System.currentTimeMillis();
        logger.info("后台获取广告时间：" + (endTime - startTime) + "ms");
        Page<AdDTO> page = new Page(new PageInfo<>(result));
        return page;
    }

    @Override
    public List<ColumnProdDTO> adRelyColumnProd(AdDTO adDTO) {
        List<ColumnProdDTO> columnProdDTOS = columnProdDao.adRelyColumnProd(adDTO);
        return columnProdDTOS;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean addAd(AdDTO adDTO) {
        //校验栏目是否存在
        ColumnEntity columnEntity = columnDao.selectByPrimaryKey(adDTO.getColumnId());
        if (columnEntity == null) {
            throw new MsgException(ResponseCodeEnum.COLUMN_IS_NOT_EXIT);
        }
        //校验，如果已存在的广告名不能再添加或者修改成为此广告
        AdEntity adEntityTemp = adDao.selectAdEntityByadName(adDTO);
        if (adEntityTemp != null) {
            throw new MsgException(ResponseCodeEnum.AD_IS_EXIT);
        }
        AdEntity adEntity = new AdEntity();
        adDTO.setImgUrl(AliOSSUtil.getFilePath(adDTO.getImgUrl()));
        BeanUtils.copyProperties(adDTO, adEntity);
        adEntity.setAdName(adDTO.getTitle());
        adEntity.setSubTitle(adDTO.getTitle());
        adEntity.setPageId(1);
        //如果广告类型是2的话，adObject应该放栏目id
        //1放栏目下商品id
        //3 adObject 字段为空，但是targetUrl字段需要链接地址
        if (2 == adEntity.getAdClass()) {
            adEntity.setAdObject(adDTO.getColumnId().toString());
        }
        //初始化的广告位待发布状态
        adEntity.setAdStatus(CommonEnume.AdStatus.valueOf("c").toString());
        Integer flag = adDao.insertSelective(adEntity);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(adDTO, baseDTO);
            jmOperationLogService.insertAddLog(baseDTO, adDTO.getId() + "", "addAd", "jimi_ad", "添加广告");
            return true;
        }
        return false;
    }

    @Override
    public AdEntity gotoEditAd(AdDTO adDTO) {
        AdEntity adEntity = adDao.selectByPrimaryKey(adDTO.getId());
        //如果说广告类型为1的话，需要将商品名字返回给前段
        if (adEntity.getAdClass() == 1) {
            ProductDto productDto = productDao.findByProdId(adEntity.getAdObject());
            if (productDto != null) {
                adEntity.setProdName(productDto.getProdName());
            } else {
                adEntity.setProdName("");
            }
        }
        //添加操作日志
        jmOperationLogService.insertQueryLog(new BaseDTO(), "gotoEditAd", "jimi_ad", adDTO.getId() + "", "转跳到指定广告界面");
        adEntity.setImgUrl(AliOSSUtil.getFileUrl(adEntity.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
        return adEntity;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean editAd(AdDTO adDTO) {
        //校验栏目是否存在
        ColumnEntity columnEntity = columnDao.selectByPrimaryKey(adDTO.getColumnId());
        if (columnEntity == null) {
            throw new MsgException(ResponseCodeEnum.COLUMN_IS_NOT_EXIT);
        }
        //校验，如果已存在的广告名不能再添加或者修改成为此广告
        AdEntity adEntityTemp = adDao.selectAdEntityByadName(adDTO);
        if (adEntityTemp != null && adEntityTemp.getId().intValue() != adDTO.getId().intValue()) {
            throw new MsgException(ResponseCodeEnum.AD_IS_EXIT);
        }

        AdEntity adEntity = new AdEntity();
        if (adDTO.getImgUrl().startsWith("http")) {
            adDTO.setImgUrl(AliOSSUtil.getFilePath(adDTO.getImgUrl()));
        }
        BeanUtils.copyProperties(adDTO, adEntity);
        adEntity.setAdName(adDTO.getTitle());
        adEntity.setSubTitle(adDTO.getTitle());
        adEntity.setPageId(1);
        //如果广告类型是2的话，adObject应该放栏目id
        //1放栏目下商品id
        //3 adObject 字段为空，但是targetUrl字段需要链接地址
        if (2 == adEntity.getAdClass()) {
            adEntity.setAdObject(adDTO.getColumnId().toString());
            adEntity.setTargetUrl("");
        }
        if (1 == adEntity.getAdClass()) {
            adEntity.setTargetUrl("");
        }
        if (3 == adEntity.getAdClass()) {
            adEntity.setAdObject("");
        }
        adEntity.setModifyTime(new Date());
        Integer flag = adDao.updateByPrimaryKey(adEntity);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(adDTO, baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO, "editAd", "jimi_ad", adEntity.getId() + "", "编辑指定广告");
            return true;
        }
        return false;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean deleteAd(AdDTO adDTO) throws MsgException {
        AdEntity adEntity = adDao.selectByPrimaryKey(adDTO.getId());
        if (adEntity == null) {
            throw new MsgException(ResponseCodeEnum.AD_IS_NOT_EXIT);
        }
        //d代表已经发布，不能直接删除发布的广告，如果要删除需先下架再删除
        if (CommonEnume.AdStatus.valueOf("d").toString().equals(adEntity.getAdStatus())) {
            throw new MsgException(ResponseCodeEnum.AD_IS_PUBLISHED_CANNOT_DEL);
        }
        Integer flag = adDao.deleteByPrimaryKey(adEntity);
        if (flag > 0) {
            //添加操作日志
            jmOperationLogService.insertDeleteLog(adDTO.getAddUid(), "deleteAd", "jimi_ad", adDTO.getId() + "", "删除指定广告");
            return true;
        }
        return false;
    }

    @Override
    public boolean underAd(AdDTO adDTO) throws MsgException {
        AdEntity adEntity = adDao.selectByPrimaryKey(adDTO.getId());
        //处于已发布的广告才能撤下
        if (adEntity == null || !(CommonEnume.AdStatus.valueOf("d").toString()).equals(adEntity.getAdStatus())) {
            throw new MsgException(ResponseCodeEnum.AD_IS_NOT_EXIT_OR_PUBLISH);
        }
        adEntity.setAdStatus(CommonEnume.AdStatus.valueOf("e").toString());
        adEntity.setModifyTime(new Date());
        Integer flag = adDao.updateByPrimaryKey(adEntity);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(adDTO, baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO, "underAd", "jimi_ad", adEntity.getId() + "", "撤下广告");
            return true;
        }
        return false;
    }

    @Override
    public boolean publishAd(AdDTO adDTO) throws MsgException {
        AdEntity adEntity = adDao.selectByPrimaryKey(adDTO.getId());
        //处于待发布和撤下的广告可以发布
        if (adEntity == null || (!CommonEnume.AdStatus.valueOf("c").toString().equals(adEntity.getAdStatus())
                && !CommonEnume.AdStatus.valueOf("e").toString().equals(adEntity.getAdStatus()))) {
            throw new MsgException(ResponseCodeEnum.AD_IS_NOT_EXIT_OR_LOAODING_OR_UNDER);
        }
        ProductStatusDTO productStatusDTO = null;
        //如果广告是商品
        //判断商品是否上架，商品没上架，广告不能上架
        if (1 == adEntity.getAdClass()) {
            productStatusDTO = productStatusDao.getProductStats(adEntity.getAdObject());
            if (productStatusDTO == null || 1 != productStatusDTO.getProdStatus()) {
                throw new MsgException(ResponseCodeEnum.FAILURE, "广告下的商品未上架，广告不能上架，请确认重试！");
            }
        }

        adEntity.setAdStatus(CommonEnume.AdStatus.valueOf("d").toString());
        adEntity.setPublishMan(adDTO.getAddUid());
        adEntity.setPublishTime(adDTO.getPublishTime());
        adEntity.setEndTime(adDTO.getEndTime());
        adEntity.setModifyTime(new Date());
        Integer flag = adDao.updateByPrimaryKey(adEntity);
        if (flag > 0) {
            //添加操作日志
            BaseDTO baseDTO = new BaseDTO();
            BeanUtils.copyProperties(adDTO, baseDTO);
            jmOperationLogService.insertUpdateLog(baseDTO, "publishAd", "jimi_ad", adEntity.getId() + "", "发布广告");
            return true;
        }
        return false;
    }

    @Override
    public PageInfo<ColumnProdDTO> adRelyColumnProdPage(AdDTO adDTO) {
        PageHelper.startPage(adDTO.getCurrentPage(), adDTO.getPageSize());

        if (!StringUtil.isBlank(adDTO.getProdName())) {
            adDTO.setProdName("%" + adDTO.getProdName() + "%");
        }
        String sql = " SELECT jcp.*,ep.prod_name FROM  jimi_column_prod jcp LEFT JOIN ec_product ep ON jcp.prod_id=ep.prod_id where 1=1 and  jcp.column_id = :columnId and ep.prod_name like :prodName ORDER BY jcp.sort DESC ";
        QueryParam queryParam = new QueryParam();
        queryParam.setSql(sql);
        queryParam.setParamObject(adDTO);
        List<ColumnProdDTO> results = columnProdDao.adRelyColumnProdPage(queryParam);

        PageInfo<ColumnProdDTO> page = new PageInfo<>(results);
        return page;
    }


}
